package com.mygenostics.bo;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ShoppingCart implements Serializable {

	private static final long serialVersionUID = -1796740701546693937L;
	
    private final List<OrderedItem> orderedItems = new ArrayList<OrderedItem>();
	
	private long getNextItemId () {
		return orderedItems.size() + 1;
	}

	public List<OrderedItem> getOrderedItems() {
		return orderedItems;
	}
	
	public void updateItem(long id, GenoService service) {
		// Add new service to the shopping card
		if (id == 0l) {
			long index = getNextItemId();
			OrderedItem oi = new OrderedItem(index, service);
			orderedItems.add(oi);
		}
		// Update existing service
		else {
			Iterator<OrderedItem> it = orderedItems.iterator();
			while (it.hasNext()) {
				OrderedItem oi = it.next();
				if (oi.getItemId() == id) {
					oi.setService(service);
				}
			}
		}
	}
	
	public void removeItem(long id) {
		Iterator<OrderedItem> it = this.orderedItems.iterator();
		boolean reduce = false;
		
		while (it.hasNext()) {
			OrderedItem oi = it.next();
			long currentId = oi.getItemId();
			
			if (currentId == id) {
				it.remove();
				reduce = true;
			}
			
			if (reduce) {
				oi.setItemId(currentId - 1);
			}
		}
	}
	
	public int getServiceNum() {
		return orderedItems.size();
	}
	
	public BigDecimal getTotal() {
		
		BigDecimal total = new BigDecimal(0);
		
		Iterator<OrderedItem> it = orderedItems.iterator();
		
		if (it.hasNext()) {
			GenoService service = it.next().getService();
			total = total.add(service.getTotalPrice());
		}
		
		return total;
	}

}
